package Controller

import (
	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
	"hr-system/Global"
	"hr-system/Model"
	response "hr-system/Response"
	"time"
)

type IPostTransferController interface {
	RestController
}

type PostTransferController struct {
	DB *gorm.DB
}

func NewPostTransferController() IPostTransferController{
	db := Global.GetDB()
	return PostTransferController{DB: db}
}

func (p PostTransferController) PageList(c *gin.Context) {
	var requestEmployee Model.Employee
	_ = c.ShouldBind(&requestEmployee)
	name := requestEmployee.Name
	if name != ""{
		var selectEmployee Model.PostTransferEmployee
		// 查询
		result := p.DB.Model(&selectEmployee).Where("name=?", name).Find(&selectEmployee).RowsAffected
		if result == 0 {
			response.Fail(c, "查无相关记录", nil)
			return
		}
	}
	var record []Model.PostTransferEmployee
	p.DB.Order("id").Find(&record)
	length := len(record)
	re := make([]Model.ReturnPostTransfer, 0)
	for i := 0; i < length; i++ {
		var tempE Model.Employee
		p.DB.Where("id=?",record[i].Id).First(&tempE)
		if name != "" && (name != tempE.Name) {
			continue
		}
		var tempOP Model.Post
		p.DB.Where("post_number=?",record[i].OriginPostNumber).First(&tempOP)
		var tempNP Model.Post
		p.DB.Where("post_number=?",record[i].NewPostNumber).First(&tempOP)
		re = append(re, Model.ReturnPostTransfer{
			Id:record[i].Id,
			Name:tempE.Name,
			Sex:tempE.Sex,
			OriginPostName:tempOP.PostName,
			NewPostName:tempNP.PostName,
			TransferDate:record[i].TransferDate.Format("2006-01-02"),
			ReasonsForTransfer:record[i].ReasonsForTransfer,
		})
	}

	response.Success(c, gin.H{"data": re}, "查询成功")
}

func (p PostTransferController) Create(c *gin.Context) {
	var requestEmployee Model.NewPostTransfer
	_ = c.ShouldBind(&requestEmployee)
	updateEmployee := Model.Employee{}
	result := p.DB.Where("id=?",requestEmployee.Id).First(&updateEmployee).RowsAffected
	if result == 0 {
		response.Fail(c, "该员工不存在，无法调动", nil)
		return
	}
	if updateEmployee.IsQuit == "是" {
		response.Fail(c, "该员工已离职", nil)
		return
	}
	var total int64
	p.DB.Model(Model.PostTransferEmployee{}).Count(&total)
	var tempP Model.Post
	p.DB.Where("post_name=?",requestEmployee.NewPostName).First(&tempP)
	t,_ := time.Parse("2006-01-02", requestEmployee.TransferDate)
	newRecord := Model.PostTransferEmployee{
		TransferId: int(total+1),
		Id: requestEmployee.Id,
		OriginPostNumber:updateEmployee.PostNumber,
		NewPostNumber:tempP.PostNumber,
		TransferDate:t,
		ReasonsForTransfer:requestEmployee.ReasonsForTransfer,
	}
	if newRecord.NewPostNumber == newRecord.OriginPostNumber {
		response.Fail(c, "原岗位和新岗位相同", nil)
		return
	}
	err := p.DB.Create(&newRecord).Error
	if err != nil {
		response.Fail(c, err.Error(), nil)
		return
	}
	p.DB.Model(&updateEmployee).Update("post_number",newRecord.NewPostNumber)
	if err != nil {
		response.Fail(c, err.Error(), nil)
		return
	}
	response.Success(c, gin.H{"data": requestEmployee}, "调动成功")
}
